const http = require("http");
const config = require("./config");
const querystring = require("querystring");

const app  = {
  send: ({path, method = 'get', data = {},clientReq,callback,error}) => {
    let _promise = new Promise(function (resolve,reject) {
      let 
      postData = querystring.stringify(data),
      req = http.request({
        hostname: config.hostname,
        path: config.path + path,
        method: method,
        port:8097,
        headers: {
          "Host":config.hostname,
          "Content-Type": "application/x-www-form-urlencoded",
          "Cache-Control": "no-cache",
          "Cookie":clientReq.headers.cookie || "" ,
          "X-Real-IP":clientReq.headers["x-real-ip"] || "" ,
          "X-Forwarded-For":clientReq.headers["x-forwarded-for"] || "" ,
          "User-Agent":clientReq.headers["user-agent"] || ""
        }
      },(res) => {
        console.log("状态码："+res.statusCode);
        if(res.statusCode == 200){
          var body = "";
          res.setEncoding('utf8');          
          res.on('data', (data) => { body += data;});
          res.on("end", () => {
           resolve(JSON.parse(body));
        });
        }else{
          console.log("Bad request,status is:"+res.statusCode);
          reject("Invalid data!"); 
        }
      });

      req.on("error", (e) => {
        console.log('problem with request: ' + e.message);
        reject(e); 
      });

      req.write(postData);
      req.end();
    })
    if(callback){
      _promise.then((res) => {
        callback && callback(res);
      }).catch((res) => {
        error && error(res);
      })
    }
    return _promise;
  },
  all : (arrs,callback,error) => {
    var fetchPageUrl = [];
    arrs.forEach(function (o) { 
      fetchPageUrl.push(app.send(o));  
    });  
    Promise
     .all(fetchPageUrl) 
     .then(function(objs) {
        callback && callback(objs);
     })
     .catch(function(e){
       error && error(e);
     })
   }
};
module.exports = app;